<?php
/**
 * mock_fmw_api
 * FmwDewuController.php
 * @author: Heze
 * Date: 2024/7/30 13:52
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class FmwDewuController extends Controller
{
    protected $baseUrl = 'api/dewu/';

    protected $openId = 'dewu_123456';

    protected $requestData = [];

    public function index(Request $request)
    {
        $url = $request->get('s');
        $methodUrl = str_replace($this->baseUrl, '', $url);
        $methodUrl = ltrim($methodUrl, 'v1/');
        $methodUrl = ltrim($methodUrl, 'v2/');
        if (!empty($methodUrl)) {
            $method = str_replace('/', '_', $methodUrl);
        } else {
            return [];
        }

        if (!method_exists($this, $method)) {
            echo sprintf("[%s] mock function not exists", $method);
            exit;
        }

        $this->requestData = $request->toArray();
        return $this->$method();
    }

    /**
     * @param array $data
     * @return array
     */
    protected function toResponse($data)
    {
        return [
            'msg' => 'success',
            'code' => 200,
            'data' => $data,
        ];
    }

    protected function getCurrentDate($timestamp = '')
    {
        return !empty($timestamp) ? date('Y-m-d H:i:s', $timestamp) : date('Y-m-d H:i:s');
    }


    public function oauth2_token()
    {
        $accessToken = date('YmdHis') . Str::random(6);

        return $this->toResponse([
            "scope" => ['all'],
            "open_id" => $this->openId,
            "access_token" => sprintf("dewu_token_%s", $accessToken),
            "access_token_expires_in" => 31536000,
            "refresh_token" => sprintf("dewu_refresh_token_%s", $accessToken),
            "refresh_token_expires_in" => 31536000
        ]);
    }

    public function oauth2_refresh_token()
    {
        $accessToken = date('YmdHis') . Str::random(6);

        return $this->toResponse([
            "scope" => ['all'],
            "open_id" => $this->openId,
            "access_token" => sprintf("dewu_token_%s", $accessToken),
            "access_token_expires_in" => 31536000,
            "refresh_token" => sprintf("dewu_refresh_token_%s", $accessToken),
            "refresh_token_expires_in" => 31536000
        ]);
    }

    public function order_generic_list()
    {
        $orderSn = $this->requestData['order_no'] ?? '';

        return $this->order_generic_increment($orderSn);
    }

    // 增量拉取订单（支持按类型查询）
    public function order_generic_increment($orderSn = 'FSOMS20241227714030')
    {
        $skuPrice = rand(12000, 20000);
        $skuQuantity = 2;
        $orderAmount = $skuPrice * $skuQuantity;

        $orders = [
            "order_no" => !empty($orderSn) ? $orderSn : sprintf('dewu%s%s', date('Ymd'), Str::random(6)),
            "order_type" => 0, // 0:普通现货,1:普通预售,2:立即变现,3:跨境,6:入仓,7:极速现货,8:极速预售,9:定金预售入仓,10:(非在仓)定金预售,11:汽车出价,12:品牌专供,13:品牌专供入仓,15:虚拟商品订单,21:盲盒,25:保税仓,27:虚拟卡券,36:众筹直发,37:众筹入仓,38:定金预售,100:限时折扣活动,200:跨境极速,201:跨境寄售,1000:拍卖直发,1001:拍卖寄售,1002:拍卖入仓
            "order_status" => 4000, // 1100:定金已支付(定金预售),1200:待支付尾款(定金预售),2000:支付成功,2007:待卖家发货(针对众筹订单,众筹成功),2003:待卖家接单(针对虚拟订单),2010:待平台收货,2015:待卖家接发货(针对虚拟订单),3000:平台已收货,3010:质检通过,3020:鉴别通过,3030:待平台发货,3040:待买家收货,4000:交易成功,7000:交易失败,7500:定金已支付，交易关闭(未支付尾款),8010:交易关闭成功
            "pay_status" => 2, // 0:未支付，2：已付全款
            "pay_time" => $this->getCurrentDate(),
            "amount" => $orderAmount, // 订单总金额(单位:分)
            "pay_amount" => $orderAmount, // 支付总金额(单位:分)
            "merchant_subsidy_amount" => 0, // 商家承担的优惠金额(单位:分)
            "sku_id" => 202407310001,
            "brand_id" => 2024,
            "seller_id" => 2024,
            "spu_id" => 20240731,
            "title" => "测试商品名称",
            "logo_url" => "logo_url",
            "sku_price" => $skuPrice,
            "qty" => $skuQuantity,
            "article_number" => "article_number_202407310001",
            "merchant_sku_code" => "SKUA00001",
            "properties" => "黑色",
            "poundage" => 0,
            "poundage_percent" => 0,
            "close_type" => 0, // 0:默认(无业务含义),5:交易关闭,10:超时未支付,11:买家关闭,12:超时未发货,13:质检未通过,14:鉴别未通过,15:平台取消,16:补单超时,17:补单不同意,18:退货关闭,19:申请换货,20:退货关闭, 需要退卖家,21:盲盒超时未取回,22:退货中
            "seller_bidding_no" => "seller_bidding_no_202407310001",
            "close_time" => "",
            "create_time" => $this->getCurrentDate(),
            "modify_time" => $this->getCurrentDate(),
            "delivery_limit_time" => $this->getCurrentDate(strtotime("+7 day")),
            "express_to_platform" => [
                "express_no" => date('YmdHis') . Str::random(6),
                "delivery_time" => $this->getCurrentDate(),
                "carrier" => "0",
                "sub_express_no_list" => []
            ],
            "order_qc_info" => [
                "qc_result_type" => 0, // 0：质检通过，1：质检未通过，2：质检有瑕疵，3：未开始质检，4：开始质检
                "qc_result_desc" => "质检结果描述",
                "qc_result_pics" => "质检结果图片",
                "confirm_status" => 0
            ],
            "order_identify_info" => [
                "identify_result_type" => 0, // 0：未鉴别，1：鉴别为真，2：鉴别为假，3：有瑕疵，4：开始鉴别
                "identify_result_desc" => "鉴别结果描述",
                "identify_time" => $this->getCurrentDate()
            ],
            "delivery_address_platform" => [ // 卖家发货到平台地址信息
                'name' => '何泽',
                'phone' => '1330000011',
                'mobile' => '1330000011',
                'province' => '上海',
                'city' => '上海市',
                'district' => '杨浦区',
                'street' => '互联宝地',
                'postcode' => '200082',
            ],
            "buyer_address" => "",
            "return_to_seller" => [ // 订单退货到卖家信息
//                "express_no" => "string",
//                "delivery_time" => "2022-02-16 13:38:37",
//                "carrier" => "string",
//                "sub_express_no_list" => [
//                    "string"
//                ]
            ],
            "sn_no" => "string",
            "imei_no" => "string",
            "platform_delivery_time" => $this->getCurrentDate(),
            "package_quantity" => 1,
            "delivery_address" => "delivery_address"
        ];

//        $orders['order_type'] = 6; // 入仓类型
//        $orders['order_status'] = 3040; // 待收货
//        $orders['order_status'] = 4000; // 交易成功

        $pageNo = $this->requestData['page_no'] ?? 1;
        return $this->toResponse([
            "page_size" => 30,
            "page_no" => 1,
            "total_results" => ($pageNo <= 2) ? 1 : 0,
            "orders" => ($pageNo <= 2) ? [$orders] : [],
        ]);
    }

    // 增量退货订单查询
    public function order_brand_deliver_increment()
    {
        $skuPrice = rand(12000, 20000);
        $skuQuantity = rand(1, 5);
        $orderAmount = $skuPrice * $skuQuantity;

        $orders = [
            "order_no" => sprintf('dewu_brand_%s%s', date('Ymd'), Str::random(6)),
            "order_type" => 1, // 支持的订单类型：26:品牌直发,36:众筹直发,1000:拍卖直发,39：定金预售直发
            "order_status" => 2000, // 1000:待支付，1100:定金已支付(定金预售直发特有),2000:支付成功,2007:待卖家发货(众筹直发),2010:待平台收货,2015:待卖家发货(盲盒直发),3000:平台已收货,3010:质检通过,3020:鉴别通过,3030:待平台发货,3035:待物流揽收,3040:待买家收货,4000:交易成功,7000:交易失败,8000:关闭中,8010:交易关闭成功
            "pay_status" => 2, // 0:未付款,1:已支付（品牌直发），2：已支付（其他订单类型）
            "pay_time" => $this->getCurrentDate(),
            "amount" => $orderAmount,
            "pay_amount" => $orderAmount,
            "sku_id" => 202407310001,
            "spu_id" => 20240731,
            "brand_id" => 2024,
            "title" => "测试商品名称",
            "logo_url" => "logo_url",
            "sku_price" => $skuPrice,
            "qty" => $skuQuantity,
            "properties" => "黑色",
            "poundage" => 0,
            "poundage_percent" => 0,
            "close_type" => 0, // 0:默认(无业务含义),5:交易关闭,10:超时未支付,11:买家关闭,12:超时未发货,13:质检未通过,14:鉴别未通过,15:平台取消,16:补单超时,17:补单不同意,18:退货关闭,19:申请换货,20:退货关闭, 需要退卖家,21:盲盒超时未取回,22:退货中,40:定金尾款超时未支付,50:超时未激活关单,60:卖家主动关单,61:审核通过关单
            "close_time" => "",
            "create_time" => $this->getCurrentDate(),
            "modify_time" => $this->getCurrentDate(),
            "package_quantity" => 1,
            "buyer_address" => [ // 买家收货地址信息
                "name" => "何*",
                "mobile" => "133****11",
                "province" => "北京",
                "city" => "北京市",
                "district" => "通州区",
                "detail_address" => "上海上海市杨浦区****",
            ],
            "express_to_platform" => [
                "express_no" => "SF92829232722",
                "delivery_time" => "2020-01-02 12:00:00",
                "carrier" => "SF",
                "sub_express_no_list" => [
                    "SF92829232722",
                    "SF92829232723"
                ]
            ],
            "return_to_seller" => [
//                "express_no" => "SF92829232722",
//                "delivery_time" => "2020-01-02 12:00:00",
//                "carrier" => "SF",
//                "sub_express_no_list" => [
//                    "SF92829232722",
//                    "SF92829232723"
//                ]
            ]
        ];

        $pageNo = $this->requestData['page_no'] ?? 1;

        return $this->toResponse([
            "page_size" => 30,
            "page_no" => 1,
            "total_results" => ($pageNo <= 2) ? 1 : 0,
            "orders" => ($pageNo <= 2) ? [$orders] : [],
        ]);
    }

    public function refund_order_increment()
    {
        $orders = [
            "sku_id" => 1234567,
            "title" => "测试商品",
            "refund_status" => 9000,
            "spu_id" => 7654321,
            "create_time" => $this->getCurrentDate(),
            "scene_code" => 20,
            "return_to_seller" => [
                "carrier" => "SF",
                "express_no" => "SF123456789",
                "delivery_time" => $this->getCurrentDate()
            ],
            "properties" => "30",
            "warranty_flag" => 1,
            "unconditional_return_flag" => 1,
            "order_no" => "110118801654912345",
            "refund_type" => 20,
            "refund_reason" => "不想要了",
            "refund_no" => "RE118801654912345",
            "modify_time" => $this->getCurrentDate(),
            "order_type" => 0,
            "cancel_reason" => "重新下单",
            "merchant_sku_code" => "SKUA00001",
            "other_merchant_sku_codes" => ["A-01001", "Q-01113"],
            "status" => 0,
            "pay_amount" => 10,
            "return_amount" => 10,
            "remark_content" => "备注",
            "remark_time" => $this->getCurrentDate(),
            "tag" => 1,
            "remark_operator" => "第三方软件",
            "remark_source_desc" => "dop"
        ];

        return $this->toResponse([
            "page_size" => 30,
            "page_no" => 1,
            "total_results" => ($this->requestData['page_no'] == 1) ? 1 : 0,
            "orders" => ($this->requestData['page_no'] == 1) ? [$orders] : [],
        ]);
    }

    public function common_merchant_base_info()
    {
        return $this->toResponse([
            'merchant_id' => 20240731,
            'type_id' => 0,
            'user_id' => 20240731001,
        ]);
    }

    public function refund_brand_deliver_increment()
    {
        $refund = [
            "refund_no" => sprintf('RE%s%s', date('YmdHis'), rand(1000, 9999)),
//            "order_no" => date('YmdHis'), rand(1000, 9999),
            "order_no" => 'dewu20240829zKT40O',
            "refund_status" => 2000,
            "spu_id" => 12503845,
            "sku_id" => 202407310001,
            "brand_name" => "Anine Bing",
            "article_number" => "A-08-4280-074",
            "sku_prop" => [],
            "properties" => null,
            "refundReason" => "七天无理由",
            "create_time" => date('Y-m-d H:i:s'),
            "buyer_return_message" => null,
            "picture_list" => null,
            "video_list" => null,
            "back_to_seller_logistic" => [
                [
                    "express_no" => "SF3127065600582",
                    "express_type" => "SF",
                    "create_time" => "2024-08-26 13:22:45"
                ]
            ],
            "send_to_buyer_logistic" => [],
            "refund_type" => 20, # 10：取消，20：退换货，40：自动补单，1000：维修
            "biz_type" => 1,
            "warranty_flag" => 2,
            "unconditional_return_flag" => 1,
            "cancel_reason" => null,
            "merchant_sku_code" => 'SKUA00001',
            "other_merchant_sku_codes" => null,
            "wait_seller_audit_remaining_time" => null,
            "wait_seller_receive_remaining_time" => null,
            "wait_seller_check_remaining_time" => null,
            "wait_seller_return_remaining_time" => null,
            "create_return_source" => null,
            "speed_refund_status" => null,
            "order_type" => 0,
            "reject_code" => null,
            "audit_reject_code" => null,
            "pay_amount" => 100000,
            "return_amount" => 100000,
            "remark_content" => null,
            "remark_time" => null,
            "tag" => null,
            "remark_operator" => null,
            "remark_source_desc" => null,
            "service_order_list" => [],
            "after_sale_marks" => null
        ];

        return $this->toResponse([
            "total_results" => ($this->requestData['page_no'] == 1) ? 1 : 0,
            "page_size" => 30,
            "page_no" => 1,
            "list" => ($this->requestData['page_no'] == 1) ? [$refund] : [],
        ]);
    }

    // 商家订单发货
    public function order_delivery()
    {
//        return Response([
//            "code" => 20301085,
//            "msg" => "此订单需在成交29分钟后（即2024-09-01 20:57:59后），才可以发货",
//            "data" => null,
//            "trace_id" => "0aee203966d463b40eee6c55845d48af"
//        ], 400);

        return $this->toResponse([]);
    }

    // 商家订单发货【直发类订单】
    public function order_brand_deliver_delivery()
    {
//        return Response([
//            "code" => 20301085,
//            "msg" => "此订单需在成交29分钟后（即2024-09-01 20:57:59后），才可以发货",
//            "data" => null,
//            "trace_id" => "0aee203966d463b40eee6c55845d48af"
//        ], 400);

        return $this->toResponse([]);
    }

}
